//
//  NSObject+Extension.swift
//  LXTXShop
//
//  Created by apple on 2018/4/9.
//  Copyright © 2018年 LX. All rights reserved.
//

import Foundation

extension NSObject{
    ///-验证相关
    func isMobileNumber(str: String) -> Bool{
        if str.lengthOfBytes(using: .utf8) != 11 || !str.hasPrefix("1"){
            return false
        }
        return regx(str: str, reg: "^1\\d{10}$")
    }
    
    func isQQNumber(str: String) -> Bool {
        return regx(str: str, reg: "^\\d{5,10}$")
    }
    
    func isEmailAddress(str: String) -> Bool {
        return regx(str: str, reg: "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}")
    }
    
    func isNumber(str: String) -> Bool {
        let str = str.trimmingCharacters(in: .decimalDigits)
        if str.lengthOfBytes(using: .utf8) > 0{
            return false
        }
        return true
    }
    
    func isChinese(str: String) -> Bool{
        return regx(str: str, reg: "^[\\u4E00-\\u9FFF]+$")
    }
    
    func isNumAndChar(str: String) -> Bool {
        return regx(str: str, reg: "^(?=.*[a-zA-Z])(?=.*[\\d])[\\w\\W]{%d,%d}$");
    }
    
    func openAtAppStore(_ appId: String){
        let str = String(format:"itms-apps://itunes.apple.com/app/id%@",appId)
        UIApplication.shared.openURL(URL.init(string: str)!)
    }
    
    func regx(str: String,reg: String) -> Bool {
        do{
            let regex = try NSRegularExpression.init(pattern: reg, options: .caseInsensitive)
            let result = regex.firstMatch(in: str, options: .reportProgress, range: NSRange(location: 0,length: str.lengthOfBytes(using: .utf8)))
            if !(result != nil){
                return false
            }else{
                return true
            }
        }catch{
            XLog(error.localizedDescription)
            return false
        }
    }
    
    func showToastView(str: String) {
        if str.lengthOfBytes(using: .utf8) == 0{
            return
        }
        let l = UILabel()
        l.frame = CGRect(x:110,y:205,width:100,height:150)
        l.textAlignment = .center
        l.font = FONT(16)
        l.numberOfLines = 5
        l.textColor = UIColor.white
        l.layer.masksToBounds = true
        l.layer.cornerRadius = 4
        l.backgroundColor = RGB(60, 60, 60)
        l.text = str
        let size = l.sizeThatFits(CGSize(width:200,height:150))
        l.frame = CGRect(x:(app.scWidth-size.width-20)/2,y:205,width:size.width+20,height:size.height+10)
        l.alpha = 0.7
        app.window?.addSubview(l)
        UIView.beginAnimations(nil, context: nil)
        UIView.setAnimationDelay(2.0)
        l.alpha = 0
        UIView.commitAnimations()
        l.perform(#selector(l.removeFromSuperview), with: nil, afterDelay: 2.0)
    }
}
